/**
 * 登录获取token
 */

const Router = require('koa-router')
const { TokenValidator, CannotEmptyValidator } = require('@validator/validator.js')
const { User } = require('@model/user')
const { ParameterException } = require('@core/http-exception')
const { generateToken } = require('@core/util.js')
const { WxManager } = require('@service/wx.js')
const { Auth } = require('@middlewares/auth.js')
const router = new Router()
router.prefix('/api/user')

router.post('/login', async (ctx, next) => {
  const v = await new TokenValidator().validate(ctx)
  const type = v.get('body.type')
  const email = v.get('body.email')
  const password = v.get('body.password')
  const code = v.get('body.code')
  let token
  switch(type) {
    case 100: 
      const user = await findUser(email, password)
      token = generateToken(user.id, 8)
      break
    case 200:
      token = await WxManager.byCodeToGetToken(code)
      break
    case 300:
      break
  }
  ctx.body = token
})

router.post('/verify', async (ctx, next) => {
  const v = await new CannotEmptyValidator().validate(ctx)
  const token = v.get('body.token')
  const result =  Auth.verifyToken(token)
  ctx.body = result
})

const findUser = async (email, password) => {
  const user = await User.findOne({
    where: {
      email,
      password
    }
  })
  if (!user) {
    throw new ParameterException('账号和密码不匹配')
  }
  return user
}

module.exports = router